package com.xujie.chat.kryocodec;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.xujie.chat.message.MsgHeader;
import com.xujie.chat.message.MyMessage;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;

public class KryoSerializer {

    private static final Kryo kryo = new Kryo();
    static {
        kryo.register(MyMessage.class);
        kryo.register(MyMessage[].class);
        kryo.register(MsgHeader.class);
        kryo.register(HashMap.class);
    }

    public static byte[] serialize(Object object) {
        kryo.register(object.getClass()); // 注册类

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        Output output = new Output(byteArrayOutputStream);

        kryo.writeObject(output, object); // 序列化对象
        output.close();
        return byteArrayOutputStream.toByteArray();
    }

    public static <T> T deserialize(byte[] data, Class<T> clazz) {
        kryo.register(clazz); // 注册类

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
        Input input = new Input(byteArrayInputStream);

        T object = kryo.readObject(input, clazz); // 反序列化对象
        input.close();
        return object;
    }

    public static byte[] obj2Bytes(Object object) {
        Kryo kryo = new Kryo();
        kryo.register(object.getClass()); // 注册类
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        Output output = new Output(byteArrayOutputStream);
        kryo.writeObject(output, object); // 序列化对象
        output.close();
        return byteArrayOutputStream.toByteArray(); // 返回字节数组
    }
}
